package com.journey.org.ui.video.broadcast

import android.annotation.SuppressLint
import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.viewModelScope
import com.journey.org.BR
import com.journey.org.R
import com.journey.org.app.HttpManager
import com.journey.org.app.requestBaoBase
import com.journey.org.entity.HomeRecommendEntity
import com.mvvmhabit.org.base.BaseViewModel
import com.mvvmhabit.org.base.MultiItemViewModel
import com.mvvmhabit.org.bus.event.SingleLiveEvent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind

/**
 * @Date: 2020/11/18 14:15
 * @Author:小妖
 * @Description:
 */
class BroadcastViewModel(application: Application) : BaseViewModel(application) {

    override fun onCreate() {
        super.onCreate()
        loadVideoHeaderData()
    }

    val videoUrlField = SingleLiveEvent<String>()

    val videoDesField = ObservableField<String>()

    val videoTitleField = ObservableField<String>()

    val videoTimeField = ObservableField<String>()

    val videoContentField = ObservableField<String>()

    val items = ObservableArrayList<MultiItemViewModel<BroadcastViewModel>>()

    val itemBinding =
        ItemBinding.of<MultiItemViewModel<BroadcastViewModel>> { itemBinding, _, item ->
            when (item.getItemType().toString()) {
                "header" -> {
                    itemBinding.set(BR.viewModel, R.layout.bradcast_header_item)
                }

                "body" -> {
                    itemBinding.set(BR.viewModel, R.layout.bradcast_body_item)
                }
            }
        }

    fun loadVideoHeaderData() {
        items.clear()
        val headerViewModel = BroadcastHeaderItemViewModel(
            this,
            videoTitleField.get()!!,
            videoContentField.get()!!,
            videoDesField.get()!!
        )
        headerViewModel.multiItemType("header")
        items.add(headerViewModel)
    }

    @SuppressLint("CheckResult")
    fun loadVideoBodyData(videoId: String) {
        requestBaoBase<List<HomeRecommendEntity>> {
            onLoader {
                HttpManager.getInstance().loadVideoDetailRecommendList(videoId)!!
            }
            onSuccess {
                if (it.isNotEmpty()) {
                    it.forEach { entity ->
                        if (entity.type == "videoSmallCard") {
                            val bodyViewModel =
                                BroadcastBodyItemViewModel(this@BroadcastViewModel, entity.data)
                            bodyViewModel.multiItemType("body")
                            items.add(bodyViewModel)
                        }
                    }
                }
            }
        }
    }
}